import {messages} from "share/common";
import React, { Component } from 'react';
import { Button } from "antd";
import 'styles/expense/attachment.scss';
import noImage from 'images/expense-detail/no-image.svg';
import { connect } from 'react-redux';
import checkedImg from 'images/expense-detail/checked.svg';
import checkedImgEn from 'images/expense-detail/checked-en.svg';
import NoFind from '../svg-component/no-find';
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png';
import DragDialog from "components/drag-dialog";

@connect(mapStateToProps, null, null, { withRef: true })
class Attachment extends Component {

  static contextTypes = {
    expenseReportInvoices: React.PropTypes.array
  };

  coordinate = {};

  constructor(props) {
    super(props);
    this.state = {
      scale: 1,
      rotateZ: 0
    };
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.state.dragDialog && (
        this.props.currentAttachment.id !== nextProps.currentAttachment.id ||
        this.props.checked !== nextProps.checked
      )
    ) {
      this.state.dragDialog.update({
        content: this.renderPopupContent(nextProps)
      })
    }
  }

  componentWillUnmount() {
    this.state.dragDialog && this.state.dragDialog.destroy();
  }

  componentDidMount(){
    this.props.isPopup && this.handlePopup()
  }
  handleMouseLeave = (e) => {
    e.stopPropagation();
    this.coordinate = {};
    this.isMoving = false;
  };

  handleMouseDown = (e) => {
    e.stopPropagation();
    const { scale } = this.state;
    if (scale === 1) {
      return;
    }
    setTimeout(() => {
      this.isMoving = true;
    }, 100);
  };

  handleMouseUp = (e) => {
    e.stopPropagation();
    const { scale } = this.state;
    if (scale === 1) {
      this.handleOperate('zoom-in');
    }

    if (!this.isMoving && scale === 2) {
      this.handleOperate('zoom-out');
    }

    this.isMoving = false;
  };

  handleMouseMove = (e) => {
    e.stopPropagation();
    const { scale,rotateZ } = this.state;
    const { x, y } = this.coordinate;
    if (this.isMoving && scale === 2 && x) {
      const imageDom = this.imageRef;
      if (!imageDom) return;
      let offsetX = e.clientX - x;
      let offsetY = e.clientY - y;
      let originLeft = 0;
      let originTop = 0;
      let reg3d = /\s+translate3d\((\s?-?\d+\.?\d*px),(\s?-?\d+\.?\d*px),(\s?-?\d+\.?\d*px)\)/;
      let originCoordinates = imageDom.style.transform.match(reg3d);
      if (!originCoordinates) {
        imageDom.style.transform = imageDom.style.transform + ' translate3d(0px, 0px, 0px)';
      } else {
        originLeft = Number(originCoordinates[1].substr(0, originCoordinates[1].indexOf('px')));
        originTop = Number(originCoordinates[2].substr(0, originCoordinates[2].indexOf('px')));
      }
      let middle = offsetY;
      let sin = Math.sin(rotateZ * Math.PI  / 180);
      let cos = Math.cos(rotateZ * Math.PI / 180);
      if (sin === 1) {
        offsetY = -offsetX;
        offsetX = middle;
      }
      if (cos === -1){
        offsetY = -offsetY;
        offsetX = -offsetX;
      }
      if (sin === -1) {
        offsetY = offsetX;
        offsetX = -middle;
      }

      let translateX = originLeft + offsetX / scale;
      let translateY = originTop + offsetY / scale;
      imageDom.style.transform = imageDom.style.transform.replace(reg3d, ` translate3d(${translateX + 'px'},${translateY + 'px'},0px)`);
    }
    this.coordinate = { x: e.clientX, y: e.clientY };
  };

  getExtension = props => {
    const { currentAttachment: file = {} } = props || this.props;
    let fileName = file.fileName || file.name || (file.response ? (file.response.fileName || file.response.name || '') : '');
    if (!fileName) {
      return '';
    }
    let sections = fileName.split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    return extension.length > 3 ? extension.substring(0, 4) : extension;
  };

  handleOperate = (type) => {
    const { currentAttachment = {}} = this.props;
    if (type === 'download') {
      window.open(currentAttachment.fileURL, '_blank');
      return;
    }
    let imageDom = this.imageRef;
    if (!imageDom) return;
    let transformStyle = imageDom.style.transform;
    let rotateZ = 0,
      scale = 1;
    //得到rotateZ值
    transformStyle.replace(/rotateZ\(((\d+)|(-\d+))deg\)/, (target, $1) => {
      rotateZ = Number($1);
      return target;
    });
    //得到scale值
    transformStyle.replace(/scale\(((\d+.\d+)|(\d+))\)/, (target, $1) => {
      scale = Number($1);
      return target;
    });
    switch (type) {
      case 'zoom-in': {
        scale = 2;
        break;
      }
      case 'zoom-out': {
        scale = 1;
        break;
      }
      case 'rotate-left': {
        rotateZ -= 90;
        break;
      }
      case 'rotate-right': {
        rotateZ += 90;
        break;
      }
    }
    this.setState({ scale, rotateZ }, () => {
      imageDom.style.transform = `rotateZ(${rotateZ}deg) scale(${scale})`;
    });
  };

  getUrl = (url) => {
    let content = `https://${url.split('://')[1]}`;
    return `https://office365.huilianyi.com/?furl=${encodeURIComponent(content)}&ssl=1`;
  };

  renderImage = props => {
    const { currentAttachment = {} } = props || this.props,
      isImageFile = () => {
        let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
        return imageExtension.has(this.getExtension(props));
      },
      isIframeFile = () => {
        let allowedSuffix = ['txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'wps'];
        return allowedSuffix.has(this.getExtension(props));
      };

    if (isImageFile()) {
      return (
        <img
          onMouseUp={this.handleMouseUp}
          onMouseMove={this.handleMouseMove}
          onMouseDown={this.handleMouseDown}
          onMouseLeave={this.handleMouseLeave}
          ref={node => node ? this.imageRef = node : {}}
          draggable={false}
          style={{ cursor: this.state.scale === 1 ? 'zoom-in' : 'move' }}
          className="attachment-img"
          alt="attachment"
          src={currentAttachment.fileURL || noImage}
          onError={e => {e.target.src = defaultExpenseTypeIcon;}}
        />
      );
    } else if (isIframeFile()) {
      return React.createElement('iframe', { src: this.getUrl(currentAttachment.fileURL || noImage) });
    } else if (!currentAttachment.attachmentOID) {
      return (
        <figure>
          <img src={noImage} alt='no-image'/>
          <figcaption>{messages('expense-1.key677')/*暂无图片*/}</figcaption>
        </figure>
      );
    }
    return <NoFind/>;
  };

  renderPopupContent = props => {
    const { language, checked } = props || this.props;
    return (
      <div className="attachment-popup-image">
        {this.renderImage()}
        <img
          className={`attachment-check animated fadeIn  ${checked && 'attachment-check-been'}`}
          src={language.code === 'zh_cn' ? checkedImg : checkedImgEn}
          alt={'check'}
        />
      </div>
    )
  };

  handlePopup = () => {
    const { expenseReportInvoices: { length } } = this.context;
    const style = length === 1 ? { left: 50 } : void 0;
    const dragDialog = DragDialog.open({
      visible: true,
      content: this.renderPopupContent(),
      className: 'attachment-popup',
      name: 'expense-attachment',
      style: style,
      afterClose: () => {
        this.props.onChange(false);
        setTimeout(() => {
          this.setState({ dragDialog: undefined });
        }, 500);
      }
    });
    this.setState({ dragDialog });
    this.props.onChange(true);
  };

  render() {
    const { language, checked } = this.props;
    const { currentAttachment = {} } = this.props;
    return (
      <section className="attachment">
        {
          !this.props.isPopup && this.renderImage()
        }
        <img
          className={`attachment-check animated fadeIn  ${checked && 'attachment-check-been'}`}
          src={language.code === 'zh_cn' ? checkedImg : checkedImgEn} alt={'check'}
        />
        {
          currentAttachment.attachmentOID &&
          <Button
            className="attachment-popup-button"
            onClick={this.handlePopup}
          >
            {messages('expense-1.key731')/*弹出影像*/}
          </Button>

        }
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
  };
}

Attachment.propTypes = {
  currentAttachment: React.PropTypes.object,
  onSizeHeight: React.PropTypes.func,
  currentFlag: React.PropTypes.string,
  isPopup: React.PropTypes.bool
};

Attachment.defaultPropTypes = {
  currentAttachment: {}
};


export default Attachment;

